package xyz.jcat.web.security;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import xyz.jcat.common.Const;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

public abstract class AbstractFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 返回请求的资源需要的角色
     *
     * @param object the object being secured
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
        //请求路径
        String matchRequestUri = new StringBuilder()
                .append(Const.URL_SEPARATOR)
                .append(request.getMethod())
                .append(request.getRequestURI())
                .toString();

        Collection<RequestUriRolesConfigAttribute> requestUriRoles = getRequestUriRolesConfigAttributes();
        if(CollectionUtils.isEmpty(requestUriRoles)) {
            return null;
        }
        for (RequestUriRolesConfigAttribute requestUriRole : requestUriRoles) {
            if(antPathMatcher.match(requestUriRole.getMatchRequestUri(), matchRequestUri)) {
                return requestUriRole.getRoleConfigAttributes();
            }
        }
        return null;
    }

    public abstract Collection<RequestUriRolesConfigAttribute> getRequestUriRolesConfigAttributes();

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
